//
//  BigRecommendationItem.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/3.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import AlamofireImage

protocol GWBigRecommendationItemDelegate {
  func gwBigRecommendationItem(_ item: GWBigRecommendationItem, didTappedWithAlbumIdentifier: Int)
}

class GWBigRecommendationItem: UIView {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var coverImageContainer: UIView!
  @IBOutlet private weak var coverImageView: UIImageView!
  @IBOutlet private weak var nameLabel: UILabel!
  @IBOutlet private weak var writerNameLabel: UILabel!
  @IBOutlet private weak var readerNameLabel: UILabel!
  @IBOutlet private weak var descriptionLabel: UILabel!
  
  // MARK: - Private vars
  
  private var album: Album?
  
  // MARK: - Private methods
  
  @objc private func tapped() {
    if let album = self.album {
      delegate?.gwBigRecommendationItem(self, didTappedWithAlbumIdentifier: Int(album.id))
    }
  }
  
  // MARK: - Public vars
  
  var delegate: GWBigRecommendationItemDelegate?
  
  // MARK: - Lifecycle
  
  override func awakeFromNib() {
    super.awakeFromNib()
    
    coverImageContainer.layer.masksToBounds = false
    coverImageContainer.layer.shadowColor = UIColor.black.cgColor
    coverImageContainer.layer.shadowOpacity = 0.4
    coverImageContainer.layer.shadowOffset = CGSize(width: 0, height: 1)
    coverImageContainer.layer.shadowRadius = 5
    coverImageContainer.layer.shouldRasterize = true
    
    coverImageView.layer.cornerRadius = 5
    coverImageView.backgroundColor = UIColor(fromRGB: 0x525252)
    
    let tapGr = UITapGestureRecognizer(target: self, action: #selector(tapped))
    addGestureRecognizer(tapGr)
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  
  func prepare(album: Album) {
    self.album = album
    
    nameLabel.text = album.name
    
    if let count = album.writers?.count, count > 0 {
      writerNameLabel.text = album.writers!.map{ ($0 as! Writer).name! }.joined(separator: ",")
    } else {
      writerNameLabel.text = "未知"
    }
    
    if let count = album.readers?.count, count > 0 {
      readerNameLabel.text = album.readers!.map{ ($0 as! Reader).name! }.joined(separator: ",")
    } else {
      readerNameLabel.text = "未知"
    }
    
    descriptionLabel.text = album.getShortDescription(length: 20)
    if let url = album.cover.getURL(size: .thumb) {
      coverImageView.af_setImage(withURL: url)
    }
  }
}

extension GWBigRecommendationItem {
  static var defaultHeight: CGFloat = 142
}
